/*
 * @Author: 
 * @Date: 2024-06-11 16:08:43
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2025-01-22 18:59:59
 * @Description: 
 */
import { Provide, Config } from '@midwayjs/core';
import { AlgrithmType } from '../entity/algorithmType.entity';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, Like } from 'typeorm';
import { algorithmType, AlgorithmUpdateType } from '../interface'
import { Algorithm } from '../entity/algorithm.entity';

@Provide()
export class AlgorithmTypeService {
    @InjectEntityModel(AlgrithmType)
    AlgrithmTypeModel: Repository<AlgrithmType>;

    @InjectEntityModel(Algorithm)
    AlgorithmModel: Repository<Algorithm>;


    async algorithmTypes() {
        const algorithmTypes = await this.AlgrithmTypeModel.find({
            order: { createDate: 'ASC' },
        });
        const treeData = this.buildTree(algorithmTypes);
        return {
            succes: true,
            data: treeData,
            message: '成功',
        };
    }

    buildTree(data, parentId = '0') {
        const tree = [];
        data.forEach(item => {
            if (item.parentId === parentId) {
                const children = this.buildTree(data, item.id.toString());
                if (children.length) {
                    item.children = children;
                }
                tree.push(item);
            }
        });
        return tree;
    }
    async addType(algorithmType: algorithmType) {
        const newAlgorithmType = this.AlgrithmTypeModel.create({
            name: algorithmType.name,
            des: algorithmType.des,
            parentId: algorithmType.parentId,
            subsystemId:algorithmType.subsystemId
        });
        await this.AlgrithmTypeModel.save(newAlgorithmType);
        return { success: true, data: newAlgorithmType, message: '类型保存成功' };
    }

    async updateType(algorithmType: algorithmType) {
        try {
            // Find the existing type by its ID
            const existingType = await this.AlgrithmTypeModel.findOne({
                where: { id: algorithmType.id }
            });
    
            if (!existingType) {
                return { success: false, message: '类型未找到' };
            }
    
            // Update the fields with provided values or retain existing ones
            existingType.name = algorithmType.name || existingType.name;
            existingType.des = algorithmType.des || existingType.des;
            existingType.parentId = algorithmType.parentId || existingType.parentId;
            existingType.subsystemId = algorithmType.subsystemId || existingType.subsystemId;
    
            // Save the updated type
            const updatedType = await this.AlgrithmTypeModel.save(existingType);
    
            return { success: true, data: updatedType, message: '类型更新成功' };
        } catch (error) {
            console.error('Error updating type:', error);
            return { success: false, message: '类型更新失败，请稍后再试' };
        }
    }

    async deleteType(id: string) {
        const type = await this.AlgrithmTypeModel.findOne({
            where: {
                id,
            },
        });
        if (!type) {
            return {
                succes: false,
                message: '未查询到要删除的目录',
            };
        }
        let result = await this.AlgrithmTypeModel.remove(type);
        return {
            succes: true,
            data: result,
            message: '删除成功',
        };
    }

    async updateAlgorithmType(typeId: string, params: AlgorithmUpdateType) {
        let { added, removed } = await this.findArrayDiff(params.originAlgorithms, params.algorithms)
        console.log(added)
        console.log(removed)
        added.forEach(async algorithmId => {
            let algorithm = await this.AlgorithmModel.findOne({ where: { id: Number(algorithmId) } })
            algorithm.type.push(typeId)
            algorithm.type = this.removeDuplicates(algorithm.type)
            this.AlgorithmModel.save(algorithm)
        });

        removed.forEach(async algorithmId => {
            let algorithm = await this.AlgorithmModel.findOne({ where: { id: Number(algorithmId) } })
            algorithm.type = this.removeElement(algorithm.type, typeId)
            this.AlgorithmModel.save(algorithm)
        });
        return {
            succes: true,
            message: '算法类型批量更新成功',
        };
    }

    removeDuplicates(array: string[]): string[] {
        return Array.from(new Set(array));
    }

    removeElement<T>(array: T[], element: T): T[] {
        return array.filter(item => item !== element);
    }

    async findArrayDiff(A, B) {
        const added = [];
        const removed = [];
        const common = [];

        for (const element of B) {
            if (!A.includes(element)) {
                added.push(element);
            }
        }

        for (const element of A) {
            if (!B.includes(element)) {
                removed.push(element);
            } else {
                common.push(element);
            }
        }
        return { added, removed, common };
    }

}
